var validator_objects;
function defined(v) {
	return (typeof(v)!="undefined");
}
function insertAtCaret(element,text) {
	var txtarea = document.getElementById(element);
	var scrollPos = txtarea.scrollTop;
	var strPos = 0;
	var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
	if (br == "ie") {
		txtarea.focus();
		var range = document.selection.createRange();
		range.moveStart ('character', -txtarea.value.length);
		strPos = range.text.length;
	} else if (br == "ff")
		strPos = txtarea.selectionStart;
		var front = (txtarea.value).substring(0,strPos);
		var back = (txtarea.value).substring(strPos,txtarea.value.length);
		txtarea.value=front+text+back;strPos = strPos + text.length;
	if (br == "ie") {
		txtarea.focus();
		var range = document.selection.createRange();
		range.moveStart ('character', -txtarea.value.length);
		range.moveStart ('character', strPos);
		range.moveEnd ('character', 0);range.select();
	} else if (br == "ff") {
		txtarea.selectionStart = strPos;
		txtarea.selectionEnd = strPos;txtarea.focus();
	}
	txtarea.scrollTop = scrollPos;
}

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

function in_array(what, where) {
    for(var i=0; i<where.length; i++)
        if(what == where[i])
            return true;
    return false;
}


jQuery.noConflict();

jQuery(document).ready(function($){
	$(".can_preview_item").live('mouseover', function() {
		var rel = $(this).attr('rel');
		if (rel != undefined) {
			var info = rel.split(":");
			$(this).parent().css("position", "relative").prepend("<img src='/uploads/catalog_items/"+info[0]+"/small/"+info[1]+"' style='position: absolute; z-index: 500; left: 200px; top: 5px; border: 1px solid #ccc; padding: 3px; background: #eee;' id='can_preview_"+info[0]+"' />");
		}
	}).live('mouseout', function() {
		var rel = $(this).attr('rel');
		if (rel != undefined) {
			var info = rel.split(":");
			$("#can_preview_"+info[0]).detach();
		}
	}).live('mousemove', function (event) {
		var rel = $(this).attr('rel');
		if (rel != undefined) {
			var parent = $(this).parent().offset();
			var vleft = event.pageX - parent.left + 10;
			var vtop = event.pageY - parent.top + 10;
			var info = rel.split(":");
			$("#can_preview_"+info[0]).css("left", vleft+"px").css("top", vtop+"px");
		}
	});

	$.jStyling.createSelect($('.colored_select'));


	$('.top-menu > li').hover(function() {
		$('.top-menu > li > .toggle_class').hide();
        if($(this).children('.sub').length > 0){
			$(this).children('.toggle_class').show();
//			$('.menu_under').css('top','9px');
		}
	}, function() {
		$('.top-menu > li > .toggle_class').hide();
//		$('.menu_under').css('top','4px');

	if ($(".top-menu > li > .nohide").size() > 0) {
			$(".top-menu > li > .nohide").show();
//			$('.menu_under').css('top','9px');
	}

	});


	$("ul.opinions-paging").quickPager({pagerLocation:"both", pageSize: 20});

	$(".menu-items li a[class!='active']").parent().children("ul").hide();
	$(".menu-items li a").click(function() {
	console.log(1);
		if ($(this).parent().children('ul').size() > 0) {
			$(".menu-items li ul").slideUp();
			$(this).parent().children('ul').slideDown();
			return false;
		}

	});

	$("img.ph").parent("a").prettyPhoto();
	$("a.ph").prettyPhoto();
	$("input[type=text][id*=phone]").masker("+7 (999) 999 9999");
	var trigger = $("#over_msg").overlay({
		mask: {
			color: '#000',
			loadSpeed: 200,
			opacity: 0.5
		},
		closeOnClick: true,
		closeOnEsc: true,
		load: false,
		fixed: true,
		top: '45%',
		onBeforeLoad: function (){
			showwork();
		},
		onLoad: function () {
			hidework();
		}
	});

	$("#over_msg .close").live("click", function() {
		$("#over_msg").overlay().close();
	});

	var trigger = $("#over_ajax").overlay({
		mask: {
			color: '#000',
			loadSpeed: 200,
			opacity: 0.5
		},
		closeOnClick: true,
		closeOnEsc: true,
		load: false,
		fixed: true,
		top: '20%',
		onBeforeLoad: function (){
			showwork();
		},
		onLoad: function () {
			hidework();
		}
	});

	$("#over_ajax .close").live("click", function() {
		$("#over_ajax").overlay().close();
	});

	if ($(".opinions_form").size() > 0) {
		if (location.hash == "#form" || location.hash.match(/#opinion_[0-9]+/)) {
			$(".uline a[rel=opinions_form]").addClass("active");
			$(".uline a[rel=opinions_full]").removeClass("active");
			$(".opinions_form").removeClass('hidden');
			$(".opinions_full").addClass('hidden');
		}
	}

	$(".add-to-basket-from-list").click(function(){
		showwork();
			var id = $(this).attr('rel');
			$.ajax({
				type: "POST",
				url: "/basket/add/"+id+"/",
				data: 'count=1&id='+id,
				async: false,
				success: function(text){
					shownotice('Товар успешно добавлен в корзину');
					hidework();
					showbasket();
				}
			});
		return false;
	});
	$(".addtobasket").click(function(e) {
			showwork();
			var id = $(this).attr('rel');
			$.ajax({
				type: "POST",
				url: "/basket/add/"+id+"/",
				async: false,
				success: function(data){
					shownotice('Товар успешно добавлен в корзину', e);
					hidework();
					showbasket();
				}
			});
		return false;
	});

	$(".quote-opinion").click(function() {
		var rel = $(this).attr('rel');
		var el = $("#"+rel);
		if (el.size() > 0) {
			var text = el.find(".quote_text_ready").text();
			var topoffset = $("#opinion_simple").offset();
			$(window).scrollTop(topoffset.top);
			insertAtCaret("opinion_text-0", text);
		}
		return false;
	});

	$("img.smile").click(function() {
		var el = $(this).parent().attr("class");
		insertAtCaret(el, " "+$(this).attr('alt')+" ");
	});

	$(".show-auth-block").click(function() {
			showwork();
			var url = location.pathname.replace("/", ":");
			$.ajax({
				type: "POST",
				url: "/auth/login/"+url,
				async: false,
				success: function(data){
					$("#over_ajax").html(data).overlay().load();
					hidework();
				}
			});
		return false;
	});



	//$("input.one-size-checkbox, input.one-color-checkbox, input.counting").uniform();
	//$("input[type=text], input[type=password], select, textarea").uniform();



	$(".one-count-input").keyup(function() {
		var string = $(this).val();
		if (!string.match(/^[0-9]+$/) || string == 0) {
			$(this).val("");
		}
	}).blur(function() {
		var string = $(this).val();
		if (!string.match(/^[0-9]+$/) || string === "") {
			$(this).val("0");
		}
	});
	$(".number_of_item").live('blur', function(event) {
		var string = $(this).val();
		var rel = $(this).attr("rel");
		if (event.type != "focusout") var id = rel;
		if (!string.match(/^[0-9]+$/)) {
			$(this).val("");
		}
				showwork();
				$.ajax({
				   type: "GET",
				   url: "/basket/updatecount/"+rel+"/"+$(this).val()+"/",
				   dataType: 'html',
				   async: false,
				   success: function(data){
					   $(".update_basket_link").hide();
					   updatebasket(id);
				   }
				});
	});
	$(".number_of_item").live('keyup', function(){
		$(".update_basket_link").show();
	});
	$("#back-to-the-catalog").click(function(e){
		location.replace("/catalog/");
		e.preventDefault();
	});


	/* CATALOG */

if ($('.sale-variant-radio').size() > 0) {
	$('.sale-variant-radio[id=variant-1]').prop("checked", true);
}

	$(".sale-variant-radio").change(function() {
		$(".sale-variant").removeClass('active');
		if ($(this).attr("checked")) {
			$(this).parent().parent().parent().addClass('active');
			$(".price-value").html($(this).attr('value'));
		}

	});

	$(".tabs_heading a").click(function() {
		var rel = $(this).attr('rel');
		$(".tabs_heading a").removeClass('active');
		$(".price_place").text($(this).attr('id'));
		$(this).addClass('active');
		$(".one_tab").hide();
		$("#tab-"+rel).show();
		return false;
	});
	$(".uline a").click(function() {
		var rel = $(this).attr('rel');
		$(this).parent().children("a").removeClass('active');
		$(this).addClass('active');
		$(this).parent().parent().find(".toogle_divs div.p").hide();
		$("."+rel).show();
		if (rel != 'opinions_form')
		return false;
	});

	$(".next-image").click(function() {
		if ($(this).hasClass('disabled')) return false;
		$(".prev-image").addClass("disabled");
		$(".next-image").addClass("disabled");
		var all = $(".one-image").size();
		var now = parseInt($(".images-place-holder").css("left")) / -300 + 1;
		var count = now + 1;
		if (now < all) {
			$(".active-image-num").text(count);
			$(".images-place-holder").animate({"left": '-=300'}, null, function() {
				$(".prev-image").removeClass("disabled");
				$(".next-image").removeClass("disabled");
			});
		}
		if (now > 0) {
			$(".prev-image").show();
		}
		if (now == all - 1) {
			$(this).hide();
		}
		return false;
	});
	$(".prev-image").click(function() {
		if ($(this).hasClass('disabled')) return false;
		$(".prev-image").addClass("disabled");
		$(".next-image").addClass("disabled");
		var all = $(".one-image").size();
		var now = parseInt($(".images-place-holder").css("left")) / -300 + 1;
		var count = now - 1;
		if (now > 0) {
			$(".active-image-num").text(count);
			$(".images-place-holder").animate({"left": '+=300'}, null, function() {
				$(".prev-image").removeClass("disabled");
				$(".next-image").removeClass("disabled");
			});
		}
		if (now - 1 < all) {
			$(".next-image").show();
		}
		if (count == 1) {
			$(this).hide();
		}
		return false;
	});

	if ($(".main-slider").size() > 0) {
		$(".main-slider").each(function () {
			var slider = $(this);
			var id  = "#" + slider.attr('id');
			var items = slider.find(".items");
			var all = $(id+" > .scrollable > .items > .small-item").size();
			var max = all - 3;
			var max_left = max * 216;
			slider.find("a.prev").hide();
			if (all <= 3) {
				$(id+" > a.browse").hide();
			} else {
				$(id+" > a.next").fadeIn();
			}
			$(id+" > a.next").click(function() {
				items.animate({"left": '-=216'}, null, function() {
					left = parseInt(items.css("left")) * -1;
					if (left > 0) {
						$(id+" > a.prev").show();
					}
					if (left >= max_left) {
						$(id+" > a.next").hide();
					}
					if (left > max_left) {
						items.css("left", "-"+max_left+"px");
					}
				});
			});
			$(id+" > a.prev").click(function() {
				items.animate({"left": '+=216'}, null, function() {
					left = parseInt(items.css("left")) * -1;
					if (left == 0) {
						$(id+" > a.prev").hide();
					}
					if (left < max_left) {
						$(id+" > a.next").show();
					}
					if (left < 0) {
						items.css("left", "0px");
					}
				});
			});
		});
	}
	if ($(".main-slider-2-line").size() > 0) {
		$(".main-slider-2-line").each(function () {
			var slider = $(this);
			var id  = "#" + slider.attr('id');
			var items = slider.find(".items");
			var all = $(id+" > .scrollable > .items > .initems ").size();

			var max = all - 1;
			var max_left = max * 650;

			slider.find("a.prev").hide();
			if (all <= 1) {
				$(id+" > a.browse").hide();
			} else {
				$(id+" > a.next").fadeIn();
			}
			$(id+" > a.next").click(function() {
				items.animate({"left": '-=650'}, null, function() {
					left = parseInt(items.css("left")) * -1;
					if (left > 0) {
						$(id+" > a.prev").show();
					}
					if (left >= max_left) {
						$(id+" > a.next").hide();
					}
					if (left > max_left) {
						items.css("left", "-"+max_left+"px");
					}
				});
			});
			$(id+" > a.prev").click(function() {
				items.animate({"left": '+=650'}, null, function() {
					left = parseInt(items.css("left")) * -1;
					if (left == 0) {
						$(id+" > a.prev").hide();
					}
					if (left < max_left) {
						$(id+" > a.next").show();
					}
					if (left < 0) {
						items.css("left", "0px");
					}
				});
			});
		});
	}

	$(".ajax_notice").click(function() {
		$(this).stop().hide().html('');
	});

	$(".select-payment input").change(function(event){
		var rel = $(this).attr('value');
		$(".explane div").addClass('hidden');
		$("#ex-"+rel).removeClass('hidden');
	});

	$(".ask-question").click(function() {
		showwork();
		$.ajax({
			type: "GET",
			url: "/ask-question?item_id="+$(this).attr('rel'),
			dataType: 'html',
			async: false,
			success: function(data){
				$("#over_ajax").html(data).overlay().load();
				hidework();
			}
		});
		return false;
	});

function checkRegEmail() {
	var email = $("#simple_order_try_reg").find("#email-0").val();
	if (validate_email(email)) {
				showwork();
				$("#simple_order_try_reg").find("input[type=submit]").attr('disabled', 'disabled');
				$.ajax({
				   type: "POST",
				   url: "/auth/checkout/",
				   dataType: 'json',
				   data: 'email='+email,
				   async: false,
				   success: function(data){
					   if (data.result == true) {
						   hideFullReg();
					   } else {
						   showFullReg();
					   }
					   $("#simple_order_try_reg").find("input[type=submit]").removeAttr('disabled');
					   hidework();
				   }
				});
	}
}
function showFullReg() {
	if ($(".fullregform").size() > 0) {
		$(".fullregform").show();
		if (typeof validator_objects == 'object') {
			jQuery.each(validator_objects, function(index, element) {
				if (validator_object_simple_order_try_reg.rules[index] == undefined) {
				validator_object_simple_order_try_reg.rules[index] = element;
				}
				delete validator_objects[index];
			});
		}
	}
}
function hideFullReg() {
	if ($(".fullregform").size() > 0) {
		validator_objects = new Array();
		$(".fullregform").hide();
		var fields = new Array('email-0', 'password-0');
		jQuery.each(validator_object_simple_order_try_reg.rules, function(index, element) {
			if (element != undefined) {
				if (!in_array(element.owner, fields)) {
					validator_objects[index] = element;
					$("#"+element.owner).val("");
					delete validator_object_simple_order_try_reg.rules[index];
				}
			}
		});
	}
}

if ($('#simple_order_try_reg').size() > 0) {
	var trf = $("#simple_order_try_reg");
	if (trf.find("#email-0").size() > 0) {
		trf.find("#email-0").val("");
		trf.find("#password-0").val("");
		hideFullReg();
	}
	var emailKeyUpTimer;
	trf.find("#email-0").bind('keypress change', function() {

		if (emailKeyUpTimer) clearTimeout(emailKeyUpTimer);
		emailKeyUpTimer = setTimeout(checkRegEmail, 1500);
	});
}

	/*$("#over_ajax form").live("submit", function(e) {
		console.log('submit');
		e.preventDefault();
		return false;

	});

	/*$("#qiwi-allowed, #post-allowed").change(function() {
		var type = ($(this).attr('id') == 'qiwi-allowed'?1:0);
		showwork();
		$.ajax({
			type: "GET",
			url: "/basket/updatepayment/"+type+"/",
			dataType: 'html',
			async: false,
			success: function(data){
				updatebasket();
			}
		});
	});*/

	/* CATALOG */


//	$(".right_access").scrollable({vertical: true, circular: false});
	$(".big_center_slider").scrollable();

	$("#postpaid-allowed").live('change', function() {
		if ($(this).prop('checked') === true) {
			$(".postpaid_prices").show().parent().effect( "highlight", null, 1500);
			$(".prepaid_prices").hide();
			setCookie('basket_payment_method', 'postpaid', 864000, "/", "."+location.host);
		}
	});

	$("#prepaid-allowed").live('change', function() {
		if ($(this).prop('checked') === true) {
			$(".postpaid_prices").hide();
			$(".prepaid_prices").show().parent().effect( "highlight", null, 1500);
			setCookie('basket_payment_method', 'prepaid', 864000, "/", "."+location.host);
		}
	});

	/* FAQ */
	$(".faq-open").click(function() {
		var rel = $(this).attr('rel');
		$("#faq-"+rel).toggleClass("hidden");
	});
	/* FAQ */

});
function shownotice(string, e) {
	jQuery(".ajax_notice").stop().html(string).show().delay(1000).fadeOut();
}
function showbasket() {
		showwork();
		if (jQuery(".basket").size() > 0) {
			jQuery.ajax({
				type: "GET",
				url: "/basket/block/",
				async: false,
				success: function(data){
					jQuery(".basket").html(data).removeClass('hidden');
					hidework();
				}
			});
		} else {
			jQuery.ajax({
				type: "GET",
				url: "/basket/blocksmall/",
				async: false,
				success: function(data){
					jQuery(".compare_block").html(data).removeClass('hidden');
					hidework();
				}
			});
		}
}
function showwork() {
	jQuery(".ajax_work").show();
}
function hidework() {
	jQuery(".ajax_work").hide();
}
function updatebasket(id) {
	showwork();
	jQuery.ajax({
		type: "GET",
		url: "/basket/listing/",
		dataType: 'json',
		async: false,
		success: function(data){
			jQuery(".basket_result").html(data.text);
			if (getCookie('basket_payment_method') == "postpaid") {
				jQuery(".postpaid_prices").show();
				jQuery(".prepaid_prices").hide();
				jQuery("#postpaid-allowed").prop("checked", true);
			}
			hidework();
		}
	});
}
// VALIDATE
function validate_email(string) {
	return string.match(/^[-a-z0-9!#$%&'*+\/=?^_`{|}~]+(?:\.[-a-z0-9!#$%&'*+\/=?^_`{|}~]+)*@(?:[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?\.)*(?:aero|arpa|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|[a-z][a-z])$/i);
}
function validate_phone(string) {
	string = string.replace(/\s/gi, "");
	string = string.replace("(", "");
	string = string.replace(")", "");
	return string.match(/^\+[0-9]{11}$/i);
}
// VALIDATE